package com.wz.utils.transaction.jdbc;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;

/**
 * @Author : Wang Zhen.
 * @Date : Created in 17:01 2022/12/20
 * @Description :
 * @Modified By   :
 * @Version :
 */
public class DBConn {
	private static final String url = "jdbc:mysql://localhost:3306/test?useUnicode=true&characterEncoding=utf8&useSSL=false";
	private static final String username = "root";
	private static final String password = "xxxxxx";
	private static final String driver = "com.mysql.jdbc.Driver";
	private static Connection conn = null;

	public static Connection conn() {
		try {
			Class.forName(driver);
			try {
				conn = DriverManager.getConnection(url, username, password);
			} catch (SQLException e) {
				e.printStackTrace();
			}
		} catch (ClassNotFoundException e) {
			e.printStackTrace();
		}
		return conn;
	}

	public static void startTransaction() throws SQLException {
		if (conn != null && conn.getAutoCommit()) {
			conn.setAutoCommit(false);
		}
	}

	public static void commit() throws SQLException {
		if (conn != null && !conn.getAutoCommit()) {
			conn.commit();
		}
	}

	public static void rollback() throws SQLException {
		if (conn != null) {
			conn.rollback();
		}
	}

	public static void close() {
		if (conn != null) {
			try {
				conn.close();
			} catch (SQLException e) {
				e.printStackTrace();
			}
		}
	}
}
